<template>
  <div class="user-management">
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <!-- 搜索框 -->
      <el-input v-model="searchKeyword" placeholder="输入用户名、昵称、联系电话或创建人搜索" class="search-input" @keyup.enter="searchUsers">
        <template #append>
          <el-button type="primary" @click="searchUsers">
            <Search />
            搜索
          </el-button>
        </template>
      </el-input>

      <!-- 添加按钮和批量删除按钮 -->
      <div class="right-buttons">
        <!-- 批量删除按钮 -->
        <el-button 
          type="danger" 
          icon="Delete"          
          @click="handleBatchDelete"
          :disabled="selectedUsers.length === 0"
          style="margin-right: 8px;"
        >
          批量删除
        </el-button>
        <el-button type="primary" icon="Plus" @click="showAddDialog = true">
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <el-table :data="currentPageData" border stripe style="width: 100%" :row-key="row => row.userId"
        @selection-change="handleSelectionChange">
        <!-- 多选框列 - 添加fixed="left"属性固定在左侧 -->
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="userId" label="用户ID" width="80" align="center" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="contact" label="联系方式" width="150" />
        <el-table-column prop="avatarUrl" label="头像">
          <template #default="scope">
            <img :src="scope.row.avatarUrl" alt="头像" width="50" />
          </template>
        </el-table-column>
        <el-table-column label="角色" width="100" align="center">
          <template #default="scope">
            <el-tag :type="roleType(scope.row.roleId)" size="small">
              {{ roleName(scope.row.roleId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.creator === 'system'" type="info" size="small">系统默认</el-tag>
            <span v-else>{{ scope.row.creator || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDelete" label="删除状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isDelete === '0' ? 'success' : 'danger'">{{ scope.row.isDelete === '0' ? '未删除' : '已删除' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deleteTime" label="删除时间" width="180" align="center">
          <template #default="scope">
            {{ scope.row.deleteTime ? scope.row.deleteTime: '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后更新时间" width="180" align="center">
          <template #default="scope">
            {{ scope.row.updateTime ? scope.row.updateTime: '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updater" label="最后更新人" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.updater" type="primary" size="small">{{ scope.row.updater }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 操作列 - 添加fixed="right"属性固定在右侧 -->
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" icon="Edit" size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="danger" icon="Delete" size="small" @click="deleteUser(scope.row.userId)" style="margin-left: 8px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <el-pagination 
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px;"
    />

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加用户"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form ref="addFormRef" :model="newUser" label-width="100px" :rules="formRules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="newUser.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="newUser.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="newUser.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="newUser.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model.number="newUser.roleId" placeholder="请输入角色ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addUser">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑用户"
      width="500px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form ref="editFormRef" :model="editingUser" label-width="100px" :rules="formRules">
        <el-form-item label="用户ID">
          <el-input v-model.number="editingUser.userId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editingUser.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editingUser.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editingUser.password" type="password" placeholder="不填表示不修改"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="editingUser.contact" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="editingUser.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model.number="editingUser.roleId" placeholder="请输入角色ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateUser">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElButton, ElInput, ElTable, ElTableColumn, ElPagination, ElDialog, ElForm, ElFormItem, ElTag } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';
import { useAllUser } from '@/ViewsScript/Backend/AllUser.ts';
import { ref } from 'vue';
import type { User } from '@/ViewsScript/Backend/AllUser.ts';

// 表单验证规则
const formRules = ref({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '角色ID不能为空', trigger: 'blur' }
  ]
});

// 表单引用
const addFormRef = ref<InstanceType<typeof ElForm>>();
const editFormRef = ref<InstanceType<typeof ElForm>>();

// 存储选中的用户
const selectedUsers = ref<User[]>([]);

// 处理表格选中项变化
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection; 
};

// 角色名称映射
const roleName = (roleId: number): string => {
  const roleMap: Record<number, string> = {
    1: '管理员',
    2: '讲师',
    3: '学员'
  };
  return roleMap[roleId] || '未知角色';
};

// 角色类型(颜色)映射
const roleType = (roleId: number): string => {
  const typeMap: Record<number, string> = {
    1: 'warning',
    2: 'primary',
    3: 'success'
  };
  return typeMap[roleId] || 'default';
};

// 解构组合式函数返回的状态和方法
const {
  userList,
  showAddDialog,
  showEditDialog,
  newUser,
  editingUser,
  searchKeyword,
  currentPage,
  pageSize,
  total,
  currentPageData,
  
  fetchUsers,
  addUser,
  resetNewUser,
  deleteUser,
  editUser,
  updateUser,
  searchUsers,
  handleSizeChange,
  handleCurrentChange,
  handleBatchDelete // 添加批量删除方法
} = useAllUser(selectedUsers);
</script>

<style scoped>
/* 用户管理容器样式 */
.user-management {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  padding: 20px;
  box-sizing: border-box;
}

/* 操作按钮区域样式 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索框样式 */
.search-input {
  width: 500px;
}

/* 右侧按钮组样式 */
.right-buttons {
  display: flex;
  gap: 12px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow-y: auto;
}

/* 对话框样式 */
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.dialog-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  z-index: 2001;
  min-width: 400px;
}

.dialog-content form {
  display: flex;
  flex-direction: column;
}

.dialog-content label {
  margin-top: 10px;
}

.dialog-content input {
  margin-top: 5px;
  padding: 5px;
  height: 30px;
}

.dialog-content button {
  margin-top: 15px;
  margin-right: 10px;
  padding: 6px 12px;
  cursor: pointer;
}
</style>